package com.phoenix.shuaidatabase.utils;

import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

public class FixedWindowRateLimiter implements ShuaiRateLimiter{

    private final ConcurrentHashMap<String,FixedWindow> resources;

    public FixedWindowRateLimiter(ArrayList<String> resources,int n) {
        this.resources = new ConcurrentHashMap<>();
        for(String resource : resources) {
            this.resources.put(resource,new FixedWindow(n));
        }
    }

    @Override
    public boolean tryAcquire(String resource) {
        return resources.get(resource).isAllowed();
    }

    private static class FixedWindow {
        private final long limit; //每秒最大请求数
        private long lastTime = System.currentTimeMillis(); //上一个窗口开始的时间
        private int counter; //计数器

        public FixedWindow(long limit) {
            this.limit = limit;
        }

        public synchronized boolean isAllowed() {
            long now = System.currentTimeMillis();
            if(now - lastTime < 1000) {
                if(counter < limit) {
                    counter ++;
                    return true;
                }else {
                    return false;
                }
            }
            counter = 0;
            lastTime = now;
            return true;
        }
    }


}
